package impl

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/starmotioncf/soutchatinternal/model"
	"github.com/starmotioncf/soutchatinternal/repository"
)

type userIdRepository struct {
	*repository.Repository
}

func NewUserIdRepository(r *repository.Repository) repository.UserIdRepository {
	return &userIdRepository{
		Repository: r,
	}
}

func (r *userIdRepository) GetOne(ctx context.Context) (uint64, error) {
	var _uid sql.NullInt64
	err := r.DB(ctx).Model(&model.UserId{}).Where("status = 1").Order("sort").Limit(1).Pluck("uid", &_uid).Error
	if err != nil {
		return 0, err
	}
	return uint64(_uid.Int64), nil
}

func (r *userIdRepository) TakeOne(ctx context.Context, uid uint64) error {
	return r.DB(ctx).Model(&model.UserId{}).Where("uid = ?", uid).Update("status", 2).Error
}

func (r *userIdRepository) Create(ctx context.Context, m *model.UserId) error {
	return r.DB(ctx).Create(m).Error
}
func (r *userIdRepository) GetLastId(ctx context.Context) (lastUid uint64, err error) {
	err = r.DB(ctx).Model(&model.UserId{}).Order("uid desc").Limit(1).Pluck("uid", &lastUid).Error
	return
}

func (r *userIdRepository) GetAvailableTotal(ctx context.Context) (total int64, err error) {
	err = r.DB(ctx).Model(&model.UserId{}).Where("status = ?", 1).Count(&total).Error
	return
}

func (r *userIdRepository) CheckInCustomize(ctx context.Context, uid uint64) (bool, error) {
	var count int64
	err := r.DB(ctx).Model(&model.UserIdCustomize{}).Where("duid = ?", fmt.Sprintf("%d", uid)).Count(&count).Error
	return count > 0, err
}
